package org.rebluh.hulunbuirtravelnetworkbackendframework.service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.rebluh.hulunbuirtravelnetworkbackendframework.domain.EmailCode;
import org.rebluh.hulunbuirtravelnetworkbackendframework.repository.EmailCodeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private EmailCodeRepository emailCodeRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    public Boolean sendEmailCode(String email){
        // 获取当前时间并格式化当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);

        // 检测邮件是否频繁
        List<EmailCode> emailCodes = mongoTemplate.find(Query.query(Criteria.where("email").is(email)).with(Sort.by(Sort.Order.desc("time"))), EmailCode.class);
        // 取最近一次判断时间是否超过一分钟
        if(!emailCodes.isEmpty()){
            String emailCodeTime = String.valueOf(emailCodes.get(0).getTime());
            LocalDateTime dateTime1 = LocalDateTime.parse(formattedNow, formatter);
            LocalDateTime dateTime2 = LocalDateTime.parse(emailCodeTime, formatter);

            Duration duration = Duration.between(dateTime1, dateTime2);
            long minutesDifference = Math.abs(duration.toMinutes());

            // 两次验证码相隔时间未超过1分钟
            if (minutesDifference < 1) {
                return false;
            }
        }

        // 生成六位随机数
        Random random = new Random();
        String code = String.valueOf(100000 + random.nextInt(900000));

        // 添加数据库
        EmailCode emailCode = new EmailCode();
        emailCode.setEmail(email);
        emailCode.setCode(code);
        emailCode.setTime(formattedNow);
        emailCodeRepository.save(emailCode);

        String emailContext = """
                <div role="listitem">
                            <table width="700" border="0" align="center" cellspacing="0" style="width:700px;">
                                <tbody>
                                <tr>
                                    <td>
                                        <div style="width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;">
                                            <table border="0" cellpadding="0" cellspacing="0" width="700" height="39" style="font:12px Tahoma, Arial, 宋体;">
                                                <tbody><tr><td width="210"></td></tr></tbody>
                                            </table>
                                        </div>
                                        <div style="width:680px;padding:0 10px;margin:0 auto;">
                                            <div style="line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;">
                                                <strong style="display:block;margin-bottom:15px;">尊敬的用户：<span style="color:#f60;font-size: 16px;"></span>您好！</strong>
                                                <strong style="display:block;margin-bottom:15px;">
                                                    您本次获取的验证码为：<span style="color:#f60;font-size: 24px">{code}</span>（有效期五分钟）
                                                </strong>
                                            </div>
                                            <div style="margin-bottom:30px;">
                                                <small style="display:block;margin-bottom:20px;font-size:12px;">
                                                    <p style="color:#747474;">
                                                        注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证账户安全
                                                        <br>(工作人员不会向你索取此验证码，请勿泄漏！)
                                                    </p>
                                                </small>
                                            </div>
                                        </div>
                                        <div style="width:700px;margin:0 auto;">
                                            <div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;">
                                                <p>此为系统邮件，请勿回复<br>
                                                    请保管好您的邮箱，避免账号被他人盗用
                                                </p>
                                                <p>呼伦贝尔旅游网</p>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                """;
        emailContext = emailContext.replace("{code}", code);

        return sendEmail(email, "呼伦贝尔旅游网验证码", emailContext);
    }

    public Boolean sendEmail(String email, String title, String body){
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

            helper.setTo(email);
            helper.setSubject(title);
            helper.setText(body, true);
            helper.setFrom("admin@hulber.cn", "呼伦贝尔旅游网");

            mailSender.send(mimeMessage);
            return true;
        } catch (MessagingException | UnsupportedEncodingException e) {
            System.err.println("Error while sending email: " + e.getMessage());
            return false;
        }
    }
}
